package sword.offer;

/**
 * @author 胡宇轩
 * @Email: yuxuan.hu01@bianlifeng.com
 */
public class TwentyNine {
    public static void main(String[] args) {
        Solution solution = new Solution();
        solution.spiralOrder(new int[][]{{1,2,3},{4,5,6},{7,8,9}});
    }
    static class Solution {
        public int[] spiralOrder(int[][] matrix) {
            if(matrix.length == 0){
                return new int[]{};
            }
            int row = 0;
            int col = 0;
            int rowEdgeStart = 0;
            int colEdgeStart = 0;
            int rowEdgeEnd = matrix.length;
            int colEdgeEnd = matrix[0].length;
            int[] res = new int[matrix.length * matrix[0].length];
            int k = 0;
            while(row < rowEdgeEnd && col < colEdgeEnd){
                int flag  = 0;
                while(col < colEdgeEnd){
                    res[k++] = matrix[row][col++];
                }
                colEdgeEnd--;
                col--;
                row++;

                while(row < rowEdgeEnd){
                    res[k++] = matrix[row++][col];
                    flag = 1;
                }
                rowEdgeStart++;
                rowEdgeEnd--;
                row--;
                col--;

                while(col >= colEdgeStart && flag>=1){
                    res[k++] = matrix[row][col--];
                    flag=2;
                }
                colEdgeStart++;
                col++;
                row--;

                while(row >= rowEdgeStart && flag>=2){
                    res[k++] = matrix[row--][col];
                }
                row++;
                col++;
            }
            return res;
        }
    }
}
